import json
import os
from typing import Any, Dict, Optional, List


class ConfigManager:
    """配置管理类，负责加载和保存应用程序配置"""
    
    def __init__(self, config_file: str = "config.json"):
        """
        初始化配置管理器
        
        Args:
            config_file: 配置文件路径
        """
        self.config_file = config_file
        self.config: Dict[str, Any] = self._load_config()
    
    def _load_config(self) -> Dict[str, Any]:
        """
        加载配置文件
        
        Returns:
            配置数据字典
        """
        default_config = {
            "browser_type": "chrome",
            "iterations": 3,
            "last_prompt_file": "",
            "save_directory": os.path.expanduser("~/Documents"),
            "window_geometry": {
                "x": 100,
                "y": 100,
                "width": 800,
                "height": 600
            },
            "follow_up_prompts": [
                "基于你上面的回答，请更详细地展开第一个要点。",
                "请提供一些具体的例子或案例来说明你在上一轮回答中的观点。",
                "请总结一下我们整个对话的要点，并提出进一步的行动建议。"
            ]
        }
        
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    user_config = json.load(f)
                    # 合并用户配置和默认配置
                    for key, value in user_config.items():
                        default_config[key] = value
            except Exception as e:
                print(f"加载配置文件错误: {str(e)}")
        
        return default_config
    
    def save_config(self) -> bool:
        """
        保存配置到文件
        
        Returns:
            是否保存成功
        """
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=4, ensure_ascii=False)
            return True
        except Exception as e:
            print(f"保存配置文件错误: {str(e)}")
            return False
    
    def get(self, key: str, default: Any = None) -> Any:
        """
        获取配置值
        
        Args:
            key: 配置键名
            default: 默认值
            
        Returns:
            配置值
        """
        return self.config.get(key, default)
    
    def set(self, key: str, value: Any) -> None:
        """
        设置配置值
        
        Args:
            key: 配置键名
            value: 配置值
        """
        self.config[key] = value
    
    def update_window_geometry(self, x: int, y: int, width: int, height: int) -> None:
        """
        更新窗口几何信息
        
        Args:
            x: 窗口x坐标
            y: 窗口y坐标
            width: 窗口宽度
            height: 窗口高度
        """
        self.config["window_geometry"] = {
            "x": x,
            "y": y,
            "width": width,
            "height": height
        }
    
    def get_window_geometry(self) -> Dict[str, int]:
        """
        获取窗口几何信息
        
        Returns:
            窗口几何信息字典
        """
        return self.config.get("window_geometry", {
            "x": 100,
            "y": 100,
            "width": 800,
            "height": 600
        }) 